<template>
  <div class="crm-page customer-add-page">
    <div class="page-header">{{ title }}订单</div>
    <div class="page-content transparent">
      <div class="page-card">
        <div class="card-title">
          <el-button class="back-btn" size="medium" type="text" icon="el-icon-back" @click="goMainBack()">返回</el-button>
        </div>
        <el-form ref="form" :model="form" label-width="120px" :rules="rules">
          <div class="page-card-content">
            <div class="item-title" style="margin-top:20px">
              基本信息
            </div>
            <div class="card-item">
              <el-row :gutter="10">
                <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
                  <el-form-item label="订单编号" prop="no">
                    <el-input v-model="form.no" placeholder="根据规则自动生成" disabled maxlength="50" />
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
                  <el-form-item label="客户名" prop="customerId">
                    <VbSelect v-model="form.customerId" :name="form.customerName" style="width:100%" :load-data="loadCustomerData" @change="handleChangeCustomer" />
                  </el-form-item>
                </el-col>
                <!-- <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
                  <el-form-item label="单据状态" prop="status">
                    <el-select v-model="form.status" disabled style="width:100%">
                      <el-option v-for="cs in orderStatus" :key="cs.value" :value="cs.value" :label="cs.label" />
                    </el-select>
                  </el-form-item>
                </el-col> -->
                <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
                  <el-form-item label="所有人" prop="owner">
                    <el-input v-model="form.owner" placeholder="" maxlength="50" disabled readonly />
                  </el-form-item>
                </el-col>

                <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
                  <el-form-item label="合同编号" prop="contractId">
                    <VbSelect v-model="form.contractId" :name="form.contractNumber" style="width:100%" :load-data="loadContractData" @change="handleChangeContract" />
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
                  <el-form-item label="下单日期" prop="placeOrderDate">
                    <el-date-picker
                      v-model="form.placeOrderDate"
                      style="width:100%"
                      type="date"
                      placeholder="选择日期"
                    />
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
                  <el-form-item label="开票地址" prop="invoiceAddressId">
                    <el-select v-model="form.invoiceAddressId" style="width:100%">
                      <el-option v-for="cs in invoiceList" :key="cs.value" :value="cs.value" :label="cs.label" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
                  <el-form-item label="收货地址" prop="receiveAddressId">
                    <el-select v-model="form.receiveAddressId" style="width:100%">
                      <el-option v-for="cs in receiveList" :key="cs.value" :value="cs.value" :label="cs.label" />
                    </el-select>
                  </el-form-item>
                </el-col>

                <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
                  <el-form-item label="整单折扣%" prop="discount">
                    <el-input v-model="form.discount" v-checkMoney placeholder="请输入整单折扣" maxlength="5" />
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
                  <el-form-item label="订单金额（元）" prop="amount">
                    <el-input v-model="totalAmount" disabled placeholder="请输入报价金额" maxlength="12" />
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
                  <el-form-item label="备注" prop="remark">
                    <el-input v-model="form.remark" type="textarea" :rows="5" placeholder="请输入备注" maxlength="255" />
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </div>

          <div class="page-card-content">
            <div class="item-title" style="margin-top:20px">
              添加明细
            </div>

            <div class="card-item" style="display: flex;justify-content: space-between;align-items: center;">
              <div style="color:#666;font-size:12px">已添加数据条数（{{ form.orderDetailList.length }}）条</div>
              <el-button type="primary" @click="addTableRow('orderDetailList')">添加</el-button>
            </div>
            <el-form-item prop="orderDetailList" label-width="0">
              <div class="card-item" style="padding-top:5px">
                <el-table
                  border
                  :data="form.orderDetailList"
                >
                  <el-table-column label="产品名称">
                    <template slot="header">
                      <span class="is-required-cloum">产品名称</span>
                    </template>
                    <template slot-scope="{row,$index}">
                      <el-form-item
                        :prop="`orderDetailList[${$index}].productName`"
                        :rules="[
                          { required: true, message: '产品名称不能为空', trigger: 'blur' }
                        ]"
                      >
                        <el-input v-model="row.productName" placeholder="产品名称" />
                        <div slot="error" slot-scope="scope" class="cus-item-error">
                          {{ scope.error }}
                        </div>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column label="产品编码">
                    <template slot-scope="{row}">
                      <el-input v-model="row.productCode" placeholder="产品编码" />
                    </template>
                  </el-table-column>
                  <el-table-column label="单价">
                    <template slot="header">
                      <span class="is-required-cloum">单价</span>
                    </template>

                    <template slot-scope="{row,$index}">
                      <el-form-item
                        :prop="`orderDetailList[${$index}].unitPrice`"
                        :rules="rules.unitPrice"
                      >
                        <el-input v-model="row.unitPrice" v-checkMoney placeholder="单价" class="num-input" maxlength="13" />
                        <div slot="error" slot-scope="scope" class="cus-item-error">
                          {{ scope.error }}
                        </div>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <!-- <el-table-column label="发货仓库">
                    <template slot-scope="{row}">
                      <el-input v-model="row.warehouseId" placeholder="发货仓库" />
                    </template>
                  </el-table-column> -->
                  <el-table-column label="数量">
                    <template slot="header">
                      <span class="is-required-cloum">数量</span>
                    </template>
                    <template slot-scope="{row,$index}">
                      <el-form-item
                        :prop="`orderDetailList[${$index}].num`"
                        :rules="rules.num"
                      >
                        <el-input v-model="row.num" placeholder="数量" class="num-input" maxlength="11" @blur="inputNumBlur($index)" />
                        <div slot="error" slot-scope="scope" class="cus-item-error">
                          {{ scope.error }}
                        </div>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column label="单位">
                    <template slot-scope="{row}">
                      <el-input v-model="row.unit" placeholder="单位" />
                    </template>
                  </el-table-column>
                  <el-table-column label="最小起订量">
                    <template slot-scope="{row}">
                      <el-input v-model="row.minNum" class="num-input" maxlength="11" style="text-align:right" placeholder="最小起订量" />
                    </template>
                  </el-table-column>
                  <el-table-column label="规格">
                    <template slot-scope="{row}">
                      <el-input v-model="row.specs" placeholder="规格" />
                    </template>
                  </el-table-column>
                  <el-table-column v-if="false" label="折扣">
                    <template slot-scope="{row}">
                      <el-input v-model="row.discount" placeholder="折扣" class="num-input" max="5" />
                    </template>
                  </el-table-column>
                  <el-table-column label="金额">
                    <template slot="header">
                      <span class="is-required-cloum">金额（元）</span>
                    </template>
                    <template slot-scope="{row}">
                      <el-input v-model="row.amount" readonly placeholder="金额" maxlength="13" class="num-input" />
                    </template>
                  </el-table-column>
                  <el-table-column label="交货日期">
                    <template slot="header">
                      <span class="is-required-cloum">交货日期</span>
                    </template>
                    <template slot-scope="{row,$index}">
                      <el-form-item
                        :prop="`orderDetailList[${$index}].deliveryDate`"
                        :rules="[
                          { required: true, message: '交货日期不能为空', trigger: ['blur','change'] }
                        ]"
                      >
                        <el-date-picker
                          v-model="row.deliveryDate"
                          style="width:100%"
                          type="date"
                          placeholder="选择日期"
                        />
                        <div slot="error" slot-scope="scope" class="cus-item-error">
                          {{ scope.error }}
                        </div>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column label="备注">
                    <template slot-scope="{row}">
                      <el-input v-model="row.remark" style="width:100%" maxlength="255" />
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="操作"
                    fixed="right"
                    width="100"
                    class-name="table-opt-col"
                  >
                    <template slot-scope="{row,$index}">
                      <el-button type="text" @click="handleDelete(row,$index)">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-form-item>
          </div>
          <div class="page-card-content" style="padding-top:20px">
            <el-row style="text-align:right">
              <el-button plain @click="handleClose">取消</el-button>
              <el-button type="primary" @click="submitForm">保存</el-button>
            </el-row>
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>
<script>
import BigNumber from 'bignumber.js'
import dayjs from 'dayjs'

import { getCustomerSelect, getCustomer } from '@/api/customer'
import { getContractSelect, getContract } from '@/api/contract'
import { getOrder, saveOrder, updateOrder } from '@/api/order'
import { orderStatus, currencys } from '@/utils/enums'
import { formatTime } from '@/utils/tools'

export default {
  name: 'OrderAdd',
  components: { },
  data() {
    const validateNum = (rule, value, callback) => {
      const num = new BigNumber(value)
      const i = rule.field.replace(/[^\d]/g, '')
      const minNum = this.form.orderDetailList[i].minNum

      console.log(num)
      if (num.isNaN()) {
        callback(new Error('必须是数字'))
      } else if (num.comparedTo(0) <= 0) {
        callback(new Error('数字必须大于0'))
      } else if ((num.comparedTo(minNum) < 0)) {
        callback(new Error('数量不能小于最小起订量'))
      } else {
        callback()
      }
    }
    const validateMoney = (rule, value, callback) => {
      const num = new BigNumber(value)
      if (num.isNaN()) {
        callback(new Error('必须是数字'))
      } else if (num.comparedTo(0) <= 0) {
        callback(new Error('数字必须大于0'))
      } else {
        callback()
      }
    }
    const validateList = (rule, value, callback) => {
      if (value && value.length > 0) {
        callback()
      } else {
        callback(new Error('必须填写明细'))
      }
    }
    return {
      orderStatus,
      currencys,
      billList: [],
      receiveList: [],
      invoiceList: [],
      form: {
        'amount': '',
        'contractId': '',
        'contractNumber': '',
        'customerId': '',
        'discount': '100.00',
        'invoiceAddressId': '',
        'placeOrderDate': dayjs(),
        'receiveAddressId': '',
        'remark': '',
        'status': 1,
        orderDetailList: [],
        owner: ''
      },
      rules: {
        name: [
          { required: true, message: '报价单名称不能为空', trigger: 'blur' }
        ],
        customerId: [
          { required: true, message: '客户名不能为空', trigger: 'blur' }
        ],
        contractId: [
          { required: true, message: '合同编号不能为空', trigger: 'blur' }
        ],
        placeOrderDate: [
          { required: true, message: '下单日期不能为空', trigger: 'blur' }
        ],
        num: [
          { validator: validateNum, trigger: 'blur' }
        ],
        unitPrice: [
          // validateMoney
          { validator: validateMoney, trigger: 'blur' }

        ],
        orderDetailList: [
          { validator: validateList, trigger: 'blur' }
        ],
        currency: [
          { required: true, message: '币种不能为空', trigger: 'blur' }
        ],
        rate: [
          { required: true, message: '汇率不能为空', trigger: 'blur' }
        ]

      }
    }
  },
  computed: {
    title() {
      return this.form.id ? '修改' : '新增'
    },
    totalAmount() {
      const total = this.form.orderDetailList.map(m => m.amount).reduce(function(prev, cur, index, arr) {
        console.log(prev, cur, index)
        return BigNumber(prev).plus(cur).toFixed(2)
      }, 0)
      let discountAmout = 0
      console.log('this.form.discount:', this.form.discount)
      if (this.form.discount) {
        discountAmout = BigNumber(total).multipliedBy(this.form.discount).dividedBy(100).toFixed(2)
      } else {
        discountAmout = total
      }
      return discountAmout
    }

  },
  watch: {
    'form.orderDetailList': {
      handler(newList) {
        // 循环遍历
        newList.forEach(item => {
          item.amount = new BigNumber(item.num || 0).multipliedBy(item.unitPrice || 0).toFixed(2)
          // if (item.num < item.minNum) {
          //   item.num = item.minNum
          // }
        })
      },
      deep: true,
      immediate: true
    }

  },
  mounted() {
    const id = this.$route.query.id
    if (id) {
      getOrder({ id }).then(res => {
        this.form = res
        if (res.customerId) {
          this.getAddress(res.customerId)
        }
      })
    } else {
      this.form.owner = this.USER.userName
      const customerId = this.$route.query.customerId
      const customerName = this.$route.query.customerName
      if (customerId && customerName) {
        this.form.customerId = customerId
        this.form.customerName = customerName
        this.handleChangeCustomer({ id: customerId })
      }
      const contractId = this.$route.query.contractId
      const contractNo = this.$route.query.contractNo
      if (contractId && contractNo) {
        this.form.contractId = contractId
        this.form.contractNumber = contractNo
        // this.handleChangeContract({ id: contractId })
      }
    }
  },
  methods: {
    formatTime,
    loadContractData(params) {
      return getContractSelect(params).then(res => {
        return res
      })
    },
    loadCustomerData(params) {
      return getCustomerSelect(params).then(res => {
        return res
      })
    },
    handleChangeCustomer(v) {
      this.form.receiveAddressId = ''
      this.form.invoiceAddressId = ''
      this.getAddress(v.id)
    },
    getAddress(id) {
      getCustomer({ id }).then(res => {
        this.invoiceList = res.invoiceList ? res.invoiceList.map(m => {
          return {
            value: m.id,
            label: `${m.province}${m.city}${m.county}${m.address}`
          }
        }) : []
        this.receiveList = res.receiveList ? res.receiveList.map(m => {
          return {
            value: m.id,
            label: `${m.province}${m.city}${m.county}${m.address}`
          }
        }) : []
      })
    },
    handleChangeContract(v) {
      // 获取地址
      getContract({ id: v.id }).then(res => {
        this.form.contractNumber = res.number
      })
    },
    handleClose() {
      this.$router.back()
    },
    inputNumBlur(i) {
      console.log('122:', i)
    },
    handleDelete(row, i) {
      // 111
      console.log('1111:', i)
      this.form.orderDetailList.splice(i, 1)
    },
    addTableRow(t) {
      this.form[t].push({
        'amount': 0,
        'deliveryDate': '',
        'deliveryWarehouse': '',
        'discount': '',
        'minNum': 1,
        'num': 1,
        'productCode': '',
        'productName': '',
        'remark': '',
        'specs': '',
        'unit': '',
        'unitPrice': '',
        'warehouseId': ''
      })
    },
    inputBlur() {

    },

    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.form.amount = this.totalAmount
          // 有id 是修改
          if (this.form.id) {
            updateOrder(this.form).then(res => {
              console.log('updateQuote:', res)
              this.$message({
                type: 'success',
                message: '修改成功'
              })
              this.$router.back(-1)
            }).catch(ex => {
              this.$message({
                type: 'error',
                message: ex.message || '修改失败'
              })
            })
          } else {
            saveOrder(this.form).then(res => {
              this.$message({
                type: 'success',
                message: '新增成功'
              })
              this.$router.back(-1)
            }).catch(ex => {
              this.$message({
                type: 'error',
                message: ex.message || '新增失败'
              })
            })
          }
        }
      })
    }

  }
}
</script>
<style lang="scss">
.customer-add-page{
    .el-form-item--small.el-form-item{
      margin-bottom: 0;
    }
    .num-input.el-input--small .el-input__inner{
      text-align: right;
    }

}

</style>

